import { getShopCartList, deleteCart, updateCheckedById } from '@/api/shopCart'

const state = {
  cartList: []
}
const mutations = {
  SET_CART_LIST (state, payload) {
    state.cartList = payload
  }
}
const actions = {
  // 获取购物车列表
  async getCartList ({ commit }) {
    const res = await getShopCartList()
    // console.log('res:', res)
    commit('SET_CART_LIST', res.data)
  },
  // 删除购物车某一个商品
  async deleteCartById ({ commit }, skuId) {
    const res = await deleteCart(skuId)
    if (res.code === 200) {
      return 'ok'
    } else {
      return Promise.error(new Error('fail'))
    }
  },
  // 修改购物车商品选中状态
  async updateType ({ commit }, { skuID, isChecked }) {
    const res = await updateCheckedById(skuID, isChecked)
    if (res.code === 200) {
      return 'ok'
    } else {
      return Promise.error(new Error('fail'))
    }
  },
  // 删除选中商品
  deleteAllChecked ({ dispatch, getters }) {
    const arr = []
    getters.cartList.cartInfoList.forEach((item) => {
      if (item.isChecked) {
        const _res = dispatch('deleteCartById', item.skuId)
        arr.push(_res)
      }
    })
    // 只要有一次失败,就返回失败
    return Promise.all(arr)
  },
  // 全选 反选
  updateAllChecked ({ dispatch, getters }, value) {
    const arr = []
    getters.cartList.cartInfoList.forEach((item) => {
      if (item.isChecked !== value) {
        const _res = dispatch('updateType', {
          skuId: item.skuId,
          isChecked: value
        })
        arr.push(_res)
      }
      return Promise.all(arr)
    })
  }
}
const getters = {
  cartList (state) {
    return state.cartList[0] || {}
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
